﻿using System.Windows.Interactivity;
using System.Windows.Controls;
using System.Windows;
using System.Windows.Media;
using BBInterfaceNET.ProjectExplorer.Model;
using BBInterfaceNET.ProjectExplorer.ViewModels;

namespace BBInterfaceNET.ProjectExplorer.Behaviors
{
    internal class FocusBehavior:Behavior<TextBox>
    {

        protected override void OnAttached()
        {
            base.OnAttached();
            this.AssociatedObject.LostFocus += new System.Windows.RoutedEventHandler(AssociatedObject_LostFocus);
            this.AssociatedObject.GotFocus += new System.Windows.RoutedEventHandler(AssociatedObject_GotFocus);
        }

        void AssociatedObject_GotFocus(object sender, System.Windows.RoutedEventArgs e)
        {
            TextBox tb = sender as TextBox;
            tb.Tag = tb.Text;
            if (tb != null)
            {
                tb.SelectAll();
            }
        }

        void AssociatedObject_LostFocus(object sender, System.Windows.RoutedEventArgs e)
        {
            ExplorerViewModel vm = null;

            TextBox tb = sender as TextBox;
            ContentPresenter cp = tb.TemplatedParent as ContentPresenter;

            if (cp == null) return;

            FrameworkElement uc = VisualTreeHelper.GetParent(cp) as FrameworkElement;
            while(uc!=null)
            {
                if (uc is UserControl)
                {
                    vm = (ExplorerViewModel)uc.DataContext;
                    break;
                }
                uc = VisualTreeHelper.GetParent(uc) as FrameworkElement;
            }

            ProjectNodeBase dir = cp.DataContext as ProjectNodeBase;
            if (dir != null && dir.Editing)
            {
                vm.RenameItem(dir, tb.Tag.ToString());
            }
        }
        protected override void OnDetaching()
        {
            base.OnDetaching();
            this.AssociatedObject.LostFocus -= new System.Windows.RoutedEventHandler(AssociatedObject_LostFocus);
            this.AssociatedObject.GotFocus -= new System.Windows.RoutedEventHandler(AssociatedObject_GotFocus);
        }
    }
}
